
#include "udpcksum.h"
#include <netinet/in.h>
#include <pcap/pcap.h>
#include <stdint.h>
#include <stdio.h>

#define CMD "udp and src host %d and src port %d"

void open_output(void) {

	uint32_t localnet, netmask;
	char cmd[MAXLINE], errbuf[PCAP_ERRBUF_SIZE], str1[INET_ADDRSTRLEN], str2[INET_ADDRSTRLEN];

	struct bpf_program fcode;
	if (device == NULL) {
		
		if ((device = pcap_lookupdev(errbuf) == NULL)) {
			
			printf("error : %s.\n", errbuf);
			exit(2);
		}
	}
	printf("device = %s\n", device);
	if ((pd = pcap_open_live(device, snaplen, 0, 500, errbuf)) == NULL) {

		printf("pcap_open_live: %s\n", errbuf);
		exit(3);
	}
	if (pcap_lookupnet(device, &localnet, &netmask, errbuf) < 0) {

		printf("pcap_lookupnet : %s.\n", errbuf);
		exit(5);	
	}
	char ip_buf[32];
	{
		bzero(ip_buf, sizeof(ip_buf));
		inet_ntop(dest->sa_family, &((struct sockaddr_in*)dest)->sin_addr, ip_buf, sizeof(ip_buf));
	}
	snprintf(cmd, sizeof(cmd), CMD,  ip_buf, ntohs(((struct sockaddr_in *)dest)->sin_port));

	if (pcap_compile(pd, &fcode, cmd, 0, netmask) < 0) {

		printf("pcap complie: '%s'\n", pcap_geterr(pd));
		exit(6);
	}
	if (pcap_setfilter(pd, &fcode) < 0) {

		printf("pcap_setfilter: '%s'", pcap_geterr(pd));
		exit(7);
	}
	if ((datalink = pcap_datalink(pd)) < 0) {

		printf("pcap_datalink: '%s'.\n", pcap_geterr(pd));
	}
	printf("datalink = %d.\n", datalink);
}
